<template>
  <el-dialog :model-value="visible" title="添加用户" @close="close">
    <el-form :model="form" :rules="rules" :label-width="120">
      <el-form-item label="用户名" prop="username">
        <el-input disabled v-model="form.username" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { watch, reactive, getCurrentInstance } from 'vue';
import { getUserById, editUserApi } from '@/api/interface'

const { proxy } = getCurrentInstance() as any

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  id: Number
})
const emits = defineEmits(['close'])

watch(() => props.visible, (newVal, oldVal) => {
  if (newVal) {
    getUserById(props.id).then((res: { data: { id: undefined; username: undefined; email: undefined; mobile: undefined; }; }) => {
      form.id = res.data.id
      form.username = res.data.username
      form.email = res.data.email
      form.mobile = res.data.mobile
    })
  }
})

const form = reactive({
  id: undefined,
  username: undefined,
  email: undefined,
  mobile: undefined
})
const rules = reactive({
  username: [
    { required: true, message: '用户名是必填项', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱是必填项', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '手机号是必填项', trigger: 'blur' }
  ]
})

const submit = async () => {
  const res = await editUserApi(props.id, form)
  console.log(res);
  if (res.meta.status === 200) {
    proxy.$message.success(res.meta.msg)
    close()
  } else {
    proxy.$message.info(res.meta.msg)
  }
}

const close = () => {
  emits('close')
}
</script>

<style scoped></style>